package com.smag.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.smag.common.constant.SystemConstants;
import com.smag.common.core.domain.AjaxResult;
import com.smag.common.core.domain.entity.FarmArticle;
import com.smag.common.core.domain.entity.FarmCategory;
import com.smag.common.core.domain.entity.SysUser;
import com.smag.common.core.redis.RedisCache;
import com.smag.common.enums.AppHttpCodeEnum;
import com.smag.common.exception.base.BaseException;
import com.smag.common.utils.SecurityUtils;
import com.smag.common.utils.StringUtils;
import com.smag.common.utils.bean.BeanUtils;
import com.smag.system.domain.dto.ArticleQueryDto;
import com.smag.system.domain.vo.*;
import com.smag.system.mapper.FarmArticleMapper;
import com.smag.system.mapper.FarmProductMapper;
import com.smag.system.service.FarmArticleService;
import com.smag.system.service.FarmCategoryService;
import com.smag.system.service.FarmProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 文章表(Article)表服务实现类
 *
 * @author makejava
 * @since 2023-03-29 20:47:34
 */
@Service
public class FarmArticleServiceImpl extends ServiceImpl<FarmArticleMapper, FarmArticle> implements FarmArticleService {

    @Autowired
    @Lazy
    private FarmCategoryService farmCategoryService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private FarmArticleMapper farmArticleMapper;

    @Autowired
    private FarmProductService farmProductService;

    @Autowired
    private FarmProductMapper farmProductMapper;

    @Autowired
    private FarmArticleService farmArticleService;

    @Override
    public AjaxResult getArticleList(Integer pageNum, Integer pageSize, Long categoryId) {
        LambdaQueryWrapper<FarmArticle> queryWrapper = new LambdaQueryWrapper<>();
        if(categoryId!=null && categoryId>0)
            queryWrapper.eq(FarmArticle::getCategoryId,categoryId);
        queryWrapper.eq(FarmArticle::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        queryWrapper.orderByDesc(FarmArticle::getIsTop);
        Integer count = farmArticleMapper.selectCount(queryWrapper);
        PageHelper.startPage(pageNum,pageSize);
        List<FarmArticle> farmArticles =farmArticleMapper.selectList(queryWrapper);
        farmArticles.stream()
                .map(article -> article.setCategoryName(farmCategoryService.selectFarmCategoryById(article.getCategoryId()).getName()))
                .map(article -> article.setViewCount(Long.valueOf((Integer) redisCache.getCacheMap(SystemConstants.VIEW_COUNT).get(article.getId().toString()))))
                .collect(Collectors.toList());
        List<ArticleListVo> articleListVos = BeanUtils.copyBeanList(farmArticles, ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos, (long)count);
        return AjaxResult.success(pageVo);
    }

    @Override
    public AjaxResult getArticleDetail(Long id) {
        FarmArticle farmArticle = getById(id);
        farmArticle.setViewCount(Long.valueOf((Integer) redisCache.getCacheMap(SystemConstants.VIEW_COUNT).get(id.toString())));
        ArticleDetailVo articleDetailVo = BeanUtils.copyBean(farmArticle, ArticleDetailVo.class);
        FarmCategory category = farmCategoryService.selectFarmCategoryById(articleDetailVo.getCategoryId());
        if (category != null) {
            articleDetailVo.setCategoryName(category.getName());
        }
        return AjaxResult.success(articleDetailVo);
    }

    @Override
    public AjaxResult hotArticleList() {
        //查询热门文章 封装成ResponseResult返回
        LambdaQueryWrapper<FarmArticle> queryWrapper = new LambdaQueryWrapper<>();
        //必须是正式文章
        queryWrapper.eq(FarmArticle::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        //按照浏览量进行排序
        queryWrapper.orderByDesc(FarmArticle::getViewCount);
        //最多只查询10条
        PageHelper.startPage(1,10);
        List<FarmArticle> farmArticles = list(queryWrapper);
        farmArticles.stream()
                .map(article -> article.setViewCount(Long.valueOf((Integer) redisCache.getCacheMap(SystemConstants.VIEW_COUNT).get(article.getId().toString()))))
                .collect(Collectors.toList());
        List<HotArticleVo> hotArticleVos = BeanUtils.copyBeanList(farmArticles, HotArticleVo.class);
        return AjaxResult.success(hotArticleVos);
    }

    @Override
    public AjaxResult updateViewCount(Long id) {
        //更新redis中对应的浏览量
        redisCache.incrementCacheMapValue(SystemConstants.VIEW_COUNT,id.toString(),1);
        return AjaxResult.success();
    }

    @Override
    public boolean updateArticleAvatar(Long articleId, String avatar) {
        if (farmArticleMapper.updateArticleAvatar(articleId,avatar) > 0)
            return true;
        return false;
    }

    @Override
    public List<FarmArticle> selectFarmArticleList(ArticleQueryDto articleQueryDto) {
        Long userId = SecurityUtils.getUserId();
        PageHelper.startPage(articleQueryDto.getPageNum(),articleQueryDto.getPageSize());
        LambdaQueryWrapper<FarmArticle> queryWrapper = new LambdaQueryWrapper<>();
        if(!SysUser.isAdmin(SecurityUtils.getUserId())) {
            queryWrapper.eq(FarmArticle::getCreateBy,userId);
        }
        queryWrapper.like(StringUtils.isNotEmpty(articleQueryDto.getTitle()),FarmArticle::getTitle,articleQueryDto.getTitle());
        queryWrapper.in(!Objects.isNull(articleQueryDto.getCategoryIds()),FarmArticle::getCategoryId,articleQueryDto.getCategoryIds());
        if(!articleQueryDto.getSort()) {
            queryWrapper.orderByAsc(FarmArticle::getViewCount);
        }else {
            queryWrapper.orderByDesc(FarmArticle::getViewCount);
        }
        return list(queryWrapper);
    }

    @Override
    public AjaxResult selectFarmArticleById(Long id) {
        FarmArticle farmArticle = getBaseMapper().selectById(id);
        FarmArticleVo vo = BeanUtils.copyBean(farmArticle,FarmArticleVo.class);
        Long productId = farmProductService.selectProductIdByArticleId(id);
        vo.setProductId(productId);
        return AjaxResult.success(vo);
    }

    @Override
    public boolean updateFarmArticle(FarmArticleVo farmArticleVo) {
        FarmArticle farmArticle = BeanUtils.copyBean(farmArticleVo,FarmArticle.class);
        Long articleId = farmArticleVo.getId();
        Long productId = farmArticleVo.getProductId();
        if(farmProductMapper.selectFarmProductByArticleId(articleId) == null) {
            farmProductMapper.insertProductAndArticle(articleId,productId);
            updateById(farmArticle);
            return true;
        }
        farmProductMapper.updateProductAndArticle(articleId,productId);
        return updateById(farmArticle);
    }

    @Override
    public AjaxResult deleteFarmArticleByIds(Long[] ids) {
        if (!removeByIds(Arrays.asList(ids))) {
            throw new BaseException(AppHttpCodeEnum.SYSTEM_ERROR.getMsg());
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult insertFarmArticle(FarmArticleVo farmArticleVo) {
        FarmArticle farmArticle = BeanUtils.copyBean(farmArticleVo,FarmArticle.class);
        Long productId = farmArticleVo.getProductId();
        getBaseMapper().insert(farmArticle);
        //更新redis中的文章浏览量
        LambdaQueryWrapper<FarmArticle> query = new LambdaQueryWrapper<>();
        query.eq(FarmArticle::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<FarmArticle> farmArticleList = farmArticleService.list(query);
        Map<String, Integer> viewCountMap = farmArticleList.stream()
                .collect(Collectors.toMap(article -> article.getId().toString(), article -> article.getViewCount().intValue()));
        redisCache.setCacheMap(SystemConstants.VIEW_COUNT,viewCountMap);
        //将文章和商品绑定
        if(productId != null) {
            Long articleId = farmArticleMapper.selectArticleIdByTittleAndSummary(farmArticleVo.getTitle(),farmArticleVo.getSummary());
            farmProductMapper.insertProductAndArticle(articleId,productId);
        }
        return AjaxResult.success();
    }

}
